#!/bin/sh
# 拉取新镜像，删除旧镜像，关闭容器，删除容器，重新开启新容器

nexus_username=admin
nexus_passwd=admin123
project_name=demo

nexus_repo=192.168.107.108:8083
image_name=${nexus_repo}/${project_name}
start_port=9999:9999

error() {
  echo "\033[31m$(date "+%Y-%m-%d %H:%M:%S") [error] $@ \033[0m"
}

warning() {
  echo "\033[33m$(date "+%Y-%m-%d %H:%M:%S") [warning] $@ \033[0m"
}

info() {
  echo "\033[32m$(date "+%Y-%m-%d %H:%M:%S") [info] $@ \033[0m"
}

usage() {
  echo "Usage: $0"
}

check_env() {
  ret=0

  if ! hash docker 2>/dev/null; then
    error "docker not found"
    ret=1
  fi

  if [ $ret -ne 0 ]; then
    exit 1
  fi
}

# 删除老容器
remove_container() {
  info "remove container..."

  container_id=`docker ps -a |grep ${image_name} |grep -v grep |awk '{print $1}'`
  for id in ${container_id};
  do
  docker stop ${id}
  docker rm ${id}
  done
}

# 删除老镜像
remove_images() {
  info "remove image..."

  docker rmi ${image_name}
}

# 拉取新镜像
pull_image() {
  info "pull image..."

  docker login ${nexus_repo} -u ${nexus_username} -p ${nexus_passwd}

  docker pull ${image_name}
}

restart() {
  info "restart server"

  docker run -d -p ${start_port} ${image_name}
}

check_env
remove_container
remove_images
pull_image
restart
